package com.qf.cx.simplenms.persist.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.qf.cx.simplenms.persist.dao.api.ReaderDao;
import com.qf.cx.simplenms.persist.entity.ReaderEntity;

@Repository
public class ReaderDaoImpl implements ReaderDao {
	@Autowired
	@Qualifier("hibernateSessionFactory")
	private SessionFactory sessionFactory;

	@Override
	public void addReader(ReaderEntity reader) {
		Session session = sessionFactory.getCurrentSession();
		session.save(reader);
	}

	@Override
	public void deleteReader(String name) {
		Session session = sessionFactory.getCurrentSession();
		ReaderEntity reader = session.get(ReaderEntity.class, name);
		if (reader != null) {
			session.delete(reader);
		}
	}

	@Override
	public void updateReader(ReaderEntity reader) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(reader);
	}

	@Override
	public ReaderEntity getReader(String name) {
		Session session = sessionFactory.getCurrentSession();
		ReaderEntity reader = session.get(ReaderEntity.class, name);
		return reader;
	}

	@Override
	public List<ReaderEntity> getReaders() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from ReaderEntity");
		List<ReaderEntity> resultList = query.list();
		return resultList;
	}
}
